package com.wlstock.funi.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wlstock.funi.R;
import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.dao.MyAccountStockDao;
import com.wlstock.funi.model.MyAccountStocks;
import com.wlstock.funi.model.OperateModel;
import com.wlstock.funi.model.SelfFundModel;
import com.wlstock.funi.ui.SelfFundSetActivity;
import com.wlstock.funi.utils.IntentContants;
import com.wlstock.funi.utils.ToastUtils;
import com.wlstock.funi.widget.TradeSelector;

import org.apache.cordova.CordovaInterfaceImpl;
import org.apache.cordova.CordovaPreferences;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewImpl;
import org.apache.cordova.PluginEntry;
import org.apache.cordova.engine.SystemWebView;
import org.apache.cordova.engine.SystemWebViewEngine;

import java.util.List;
import java.util.Locale;

public class SelfFundCordovaAdapter extends BaseAdapter implements OnClickListener {
	private Context mContext;
	private List<SelfFundModel> models;
	private WebViewClient mWebClient = new WebViewClient(){
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			return true;
		}

	};


	private CordovaPreferences preferences;
	private CordovaInterfaceImpl cordovaInterface;
	private List<PluginEntry> pluginEntries;

	public SelfFundCordovaAdapter(Context mContext){
		this.mContext = mContext;
	}

	private SelfFundCordovaAdapter(Context mContext, List<SelfFundModel> models){
		this.mContext = mContext;
		this.models   = models;  
	}

	public SelfFundCordovaAdapter(Context mContext, List<SelfFundModel> models,CordovaPreferences preferences,List<PluginEntry> pluginEntries,CordovaInterfaceImpl cordovaInterface){
		this(mContext, models);
		this.preferences = preferences;
		this.pluginEntries = pluginEntries;
		this.cordovaInterface = cordovaInterface;
	}

	
	public List<SelfFundModel> getModels() {
		return models;
	}

	public void setModels(List<SelfFundModel> models) {
		this.models = models;
	}
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return models.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return models.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	@Override
	public View getView(int position, View view, ViewGroup viewGroup) {
		// TODO Auto-generated method stub
		Holder holder = null;
		SelfFundModel selfFundModel = models.get(position);
		if (view == null) {
			view = LayoutInflater.from(mContext).inflate(R.layout.list_item_self_fund_cordova, viewGroup, false);
			holder = new Holder();
			holder.layout_top_info = (LinearLayout)view.findViewById(R.id.layout_top_info);
			holder.tv_sf_stk_info = (TextView) view.findViewById(R.id.tv_sf_stk_info);
			holder.tv_sf_stk_price_info = (TextView) view.findViewById(R.id.tv_sf_stk_price_info);
			holder.img_sf_stk_dayK = (ImageView) view.findViewById(R.id.img_sf_stk_dayK);
			holder.btn_op_buy = (Button) view.findViewById(R.id.btn_op_buy);
			holder.btn_op_sell= (Button) view.findViewById(R.id.btn_op_sell);
			holder.cordova_webview = (SystemWebView) view.findViewById(R.id.cordova_webview);
			holder.appView = initCordovaWebview(holder.cordova_webview);

			view.setTag(holder);
		}else {
			holder = (Holder) view.getTag();
		}
		holder.layout_top_info.setOnClickListener(this);
		holder.layout_top_info.setTag(selfFundModel);

		holder.tv_sf_stk_info.setText(selfFundModel.nameWithCode());
		holder.tv_sf_stk_price_info.setText(getPriceInfoText(selfFundModel));
		holder.btn_op_buy.setTag(selfFundModel);
		holder.btn_op_sell.setTag(selfFundModel);
		holder.btn_op_buy.setOnClickListener(this);
		holder.btn_op_sell.setOnClickListener(this);

		loadUrl(holder.cordova_webview,holder.appView, selfFundModel.getStkLineH5());
		return view;
	}

	private CordovaWebView initCordovaWebview(SystemWebView webView) {
		CordovaWebView appView = new CordovaWebViewImpl(new SystemWebViewEngine(webView));
		if (preferences.contains("BackgroundColor")) {
			int backgroundColor = preferences.getInteger("BackgroundColor", Color.BLACK);
			// Background of activity:
			appView.getView().setBackgroundColor(backgroundColor);
		}
		appView.getView().requestFocusFromTouch();
		if (!appView.isInitialized()) {
			appView.init(cordovaInterface, pluginEntries, preferences);
		}
		cordovaInterface.onCordovaInit(appView.getPluginManager());

		// Wire the hardware volume controls to control media if desired.
		String volumePref = preferences.getString("DefaultVolumeStream", "");
		if ("media".equals(volumePref.toLowerCase(Locale.ENGLISH))) {
			((Activity)mContext).setVolumeControlStream(AudioManager.STREAM_MUSIC);
		}
		return appView;
	}

	public void loadUrl(SystemWebView webView,CordovaWebView appView,String url) {
		if (appView == null) {
			appView = initCordovaWebview(webView);
		}
//		this.keepRunning = preferences.getBoolean("KeepRunning", true);
		appView.loadUrlIntoView(url, true);
	}


	private CharSequence getPriceInfoText(SelfFundModel selfFundModel) {
		// TODO 修饰价格信息
		if (selfFundModel.getlastClose()==0) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		sb.append("今开:").append(selfFundModel.getCurOpen()+"\n").
			append("昨收:").append(selfFundModel.getlastClose()+"\n").
			append("最高:").append(selfFundModel.gethPrice()+"\n").
			append("最低:").append(selfFundModel.getLowPrice()+"\n").
			append("现价:").append(selfFundModel.getCurPrice()+" ").append(selfFundModel.cur2CloseDisAbsDisStr());
		return sb.toString();
	}


	public class Holder{
		TextView tv_sf_stk_info;
		TextView tv_sf_stk_price_info;
		ImageView img_sf_stk_dayK;
		Button   btn_op_buy;
		Button   btn_op_sell;
		SystemWebView cordova_webview;
		CordovaWebView appView;
		LinearLayout layout_top_info;
	}


	@Override
	public void onClick(View v) {
		
		SelfFundModel model = (SelfFundModel) v.getTag();
		switch (v.getId()) {
			case R.id.btn_op_buy:
				isLogin();
				TradeSelector selB = new TradeSelector(mContext, model.getStockName(), model.getStockNo(),String.valueOf(model.getCurPrice()));
				selB.show(OperateModel.TradeType_BUY);
				break;
			case R.id.btn_op_sell:
				TradeSelector selS = new TradeSelector(mContext, model.getStockName(), model.getStockNo(),String.valueOf(model.getCurPrice()));
				selS.show(OperateModel.TradeType_SELL);
				break;
			case R.id.layout_top_info:
//				ToastUtils.showMiddleMsg(mContext, model.getStockName());
				startActivityByModel(model);
				break;
		default:
			break;
		}
		
	}

	private void startActivityByModel(SelfFundModel tmpModel) {
		Intent intent = new Intent(mContext, SelfFundSetActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString(IntentContants.INTENT_STKCODE, tmpModel.getStockNo());
		bundle.putString(IntentContants.INTENT_STKNAME, tmpModel.getStockName());
		bundle.putString(IntentContants.INTENT_CUR_PRICE, String.valueOf(tmpModel.getCurPrice()));
		bundle.putString(IntentContants.INTENT_HIGH_PRICE, String.valueOf(tmpModel.gethPrice()));
		bundle.putString(IntentContants.INTENT_LOW_PRICE, String.valueOf(tmpModel.getLowPrice()));
		bundle.putString(IntentContants.INTENT_OPEN_PRICE, String.valueOf(tmpModel.getCurOpen()));
		bundle.putString(IntentContants.INTENT_LAST_CLOSE, String.valueOf(tmpModel.getlastClose()));
		MyAccountStocks ownStock = MyAccountStockDao.getInstance(mContext).queryStock(tmpModel.getStockNo());
		if (ownStock != null) {
			bundle.putInt(IntentContants.INTENT_MODE, IntentContants.INTENT_MODE_SAILE);
		} else {
			bundle.putInt(IntentContants.INTENT_MODE, IntentContants.INTENT_MODE_BUY);
		}
		intent.putExtras(bundle);
		mContext.startActivity(intent);
	}

	private void isLogin() {
		if (!FundApplication.isLogSuccess) {
			ToastUtils.showMiddleMsg(mContext, "请先登录");
			return;
		}
	}


}
